<template>
	<view>
		<view class="chat">
			<view style="background-color: #F6F6F6; text-align: center; font-size: 28rpx; color: green;" @click="more">
				查看历史记录</view>
			<scroll-view :style="{height: `${windowHeight}rpx`}" id="scrollview" scroll-y="true" :scroll-top="scrollTop"
				:scroll-with-animation="true" class="scroll-view">
				<!-- 聊天主体 -->
				<view id="msglistview" class="chat-body">
					<!-- 聊天记录 -->
					<view v-for="(item,index) in msgList" :key="index">
						<!-- 自己发的消息 -->
						<view class="item self" v-if="item.content != ''">
							<!-- 文字内容 -->
							<view class="content right">
								<mp-html :content="item.content" />
							</view>
							<!-- 头像 -->
							<view class="avatar">
								<image :src="userInfo.avatar"></image>
							</view>
						</view>
						<!-- 机器人发的消息 -->
						<view class="item Ai" v-if="item.botContent != ''"> 
							<!-- 头像 -->
							<view class="avatar">
								<image
									src="https://img0.baidu.com/it/u=679963460,2437320185&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500">
								</image>
							</view>
							<!-- 文字内容 -->
							<view class="content left">
								<mp-html :content="item.botContent" />
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<!-- 底部消息发送栏 -->
			<!-- 用来占位，防止聊天消息被发送框遮挡 -->
			<!-- <view class="chat-bottom">
				<view class="send-msg">
					<view class="uni-textarea">
						<textarea v-model="chatMsg" maxlength="300" :show-confirm-bar="false" auto-height></textarea>
					</view>
					<button :disabled="disable" @click="handleSend" class="send-btn">{{status}}</button>
				</view>
			</view> -->
			<!-- 底部消息发送栏 -->
			<!-- 用来占位，防止聊天消息被发送框遮挡 -->
			<view class="chat-bottom" :style="{height: `${inputHeight}rpx`}">
				<view class="send-msg" :style="{bottom:`${keyboardHeight}rpx`}">
					<view class="uni-textarea">
						<textarea v-model="chatMsg" maxlength="300" confirm-type="send" @confirm="handleSend"
							:show-confirm-bar="false" :adjust-position="false" @linechange="sendHeight" @focus="focus"
							@blur="blur" auto-height></textarea>
					</view>
					<button :disabled="disable" @click="handleSend" class="send-btn">{{status}}</button>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		data
	} from '../../uni_modules/uview-ui/libs/mixin/mixin'
	export default {
		data() {
			return {
				markdown:'',
				html: '',
				disable: false,
				status: '发送',
				//键盘高度
				keyboardHeight: 0,
				//底部消息发送高度
				bottomHeight: 0,
				//滚动距离
				scrollTop: 0,
				userId: '',
				//发送的消息
				chatMsg: "",
				userInfo: {},
				msgList: [{
					botContent: "hello，请问我有什么可以帮助你的吗？",
					recordId: 0,
					titleId: 0,
					content: "",
					userId: 0
				}]
			}
		},
		updated() {
			//页面更新时调用聊天消息定位到最底部
			this.scrollToBottom();
		},
		computed: {
			windowHeight() {
				return this.rpxTopx(uni.getSystemInfoSync().windowHeight)
			},
			// 键盘弹起来的高度+发送框高度
			inputHeight() {
				return this.bottomHeight + this.keyboardHeight
			}
		},
		onPullDownRefresh() {
			let that = this;
			that.more();
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 1000)
		},
		onUnload() {
			uni.closeSocket();
			uni.offKeyboardHeightChange()
		},
		onLoad() {
			uni.onKeyboardHeightChange(res => {
				//这里正常来讲代码直接写
				//this.keyboardHeight=this.rpxTopx(res.height)就行了
				//但是之前界面ui设计聊天框的高度有点高,为了不让键盘和聊天输入框之间距离差太大所以我改动了一下。
				this.keyboardHeight = this.rpxTopx(res.height - 30)
				if (this.keyboardHeight < 0) this.keyboardHeight = 0;
			})
			this.connect();
			this.getLoginUser();
		},
		methods: {
			getLoginUser() {
				let that = this;
				that.$ajax(that.$url.getLoginUser, "GET", null, function(resp) {
					that.userInfo = resp.data.result;
				})
			},
			more() {
				let that = this;
				this.searchHistoryInfo();
			},
			searchHistoryInfo() {
				let that = this;
				let data = {
					receiverId: '',
					senderId: ''
				}
				that.$ajax(that.$url.searchInfoHistory, "POST", data, function(resp) {
					let result = resp.data.result;
					that.msgList = result;
				})
			},
			connect() {
				this.userName = uni.getStorageSync('userName');
				console.log(this.userName);
				// 创建连接
				let to = uni.getStorageSync('to');
				let from = uni.getStorageSync('userId');
				let to_name = uni.getStorageSync('to_name');
				let that = this;
				let ws = uni.connectSocket({
					url: 'wss://a5942g1060.zicp.fun/api/websocket/' + from,
					success() {
						console.log('WebSocket连接成功');
					},
					fail() {
						console.log('WebSocket连接失败');
					}
				});
				this.webSocket = ws;
				// 监听连接事件
				ws.onOpen(() => {
					console.log('WebSocket已连接');

					// 在连接成功后发送数据
					// const sendData = {
					// 	from: from, // 必须包含属性from
					// 	from_name: this.userName, // 必须包含属性from
					// 	content: this.content, // 必须包含属性content
					// 	to: to, // 必须包含属性to
					// 	to_name: to_name, // 必须包含属性to
					// 	sendToAll: false // 必须包含属性sendToAll
					// 	// 其他数据...
					// };
					// ws.send({
					// 	data: JSON.stringify(sendData)
					// });
				});

				// 监听服务器推送消息事件
				wx.onSocketMessage(data => {
					console.log('收到消息', data.data);
					that.status = "发送"
					that.disable = false
					let obj = {
						botContent: data.data,
						recordId: 0,
						titleId: 0,
						content: '',
						userId: 0
					};
					that.msgList.push(obj);
					this.msg = 'data';
				});

				// 监听错误事件
				ws.onError(error => {
					console.log('WebSocket错误', error);
				});

				// 监听关闭事件
				ws.onClose(() => {
					console.log('WebSocket已关闭');
				});

				// 发送消息
				ws.send({
					data: 'Hello WebSocket',
					success() {
						console.log('消息发送成功');
					}
				});
			},
			focus() {
				this.scrollToBottom()
			},
			blur() {
				this.scrollToBottom()
			},
			// px转换成rpx
			rpxTopx(px) {
				let deviceWidth = wx.getSystemInfoSync().windowWidth
				let rpx = (750 / deviceWidth) * Number(px)
				return Math.floor(rpx)
			},
			// 监视聊天发送栏高度
			sendHeight() {
				setTimeout(() => {
					let query = uni.createSelectorQuery();
					query.select('.send-msg').boundingClientRect()
					query.exec(res => {
						this.bottomHeight = this.rpxTopx(res[0].height)
					})
				}, 10)
			},
			// 滚动至聊天底部
			scrollToBottom(e) {
				setTimeout(() => {
					let query = uni.createSelectorQuery().in(this);
					query.select('#scrollview').boundingClientRect();
					query.select('#msglistview').boundingClientRect();
					query.exec((res) => {
						if (res[1].height > res[0].height) {
							this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
						}
					})
				}, 15)
			},
			// 发送消息
			handleSend() {
				let that = this;
				//如果消息不为空
				if (!this.chatMsg || !/^\s+$/.test(this.chatMsg)) {
					that.status = "回答中..."
					that.disable = true
					let obj = {
						botContent: "",
						receiverId: "88888888",
						titleId: 0,
						content: this.chatMsg
					}
					this.msgList.push(obj);
					this.chatMsg = '';
					that.webSocket.send({
						data: JSON.stringify(obj)
					});
					that.$ajax(that.$url.chat, "POST", obj, function(resp) {

					})
				} else {
					this.$modal.showToast('不能发送空白消息')
				}
			},
		}
	}
</script>
<style lang="scss" scoped>
	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #4F7DF5;

	view,
	button,
	text,
	input,
	textarea {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	/* 聊天消息 */
	.chat {
		.scroll-view {
			::-webkit-scrollbar {
				display: none;
				width: 0 !important;
				height: 0 !important;
				-webkit-appearance: none;
				background: transparent;
				color: transparent;
			}

			// background-color: orange;
			background-color: #F6F6F6;

			.chat-body {
				display: flex;
				flex-direction: column;
				padding-top: 23rpx;
				// background-color:skyblue;

				.self {
					justify-content: flex-end;
				}

				.item {
					display: flex;
					padding: 23rpx 30rpx;
					// background-color: greenyellow;

					.right {
						background-color: $chatContentbgc;
					}

					.left {
						background-color: #FFFFFF;
					}

					// 聊天消息的三角形
					.right::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						left: 100%;
						top: 10px;
						border: 12rpx solid transparent;
						border-left: 12rpx solid $chatContentbgc;
					}

					.left::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}

					.content {
						position: relative;
						max-width: 486rpx;
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 24rpx 24rpx;
						margin: 0 24rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 42rpx;
					}

					.avatar {
						display: flex;
						justify-content: center;
						width: 78rpx;
						height: 78rpx;
						// background: $sendBtnbgc;
						border-radius: 8rpx;
						overflow: hidden;

						image {
							width: 78rpx;
							height: 78rpx;
							align-self: center;
						}
					}
				}
			}
		}

		/* 底部聊天发送栏 */
		.chat-bottom {
			width: 100%;
			height: 177rpx;
			background: #F4F5F7;

			.send-msg {
				display: flex;
				align-items: flex-end;
				padding: 16rpx 30rpx;
				width: 100%;
				min-height: 177rpx;
				position: fixed;
				bottom: 0;
				background: #EDEDED;
			}

			.uni-textarea {
				padding-bottom: 70rpx;

				textarea {
					width: 537rpx;
					min-height: 75rpx;
					max-height: 500rpx;
					background: #FFFFFF;
					border-radius: 8rpx;
					font-size: 32rpx;
					font-family: PingFang SC;
					color: #333333;
					line-height: 43rpx;
					padding: 5rpx 8rpx;
				}
			}

			.send-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 70rpx;
				margin-left: 25rpx;
				width: 128rpx;
				height: 75rpx;
				background: $sendBtnbgc;
				border-radius: 8rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				line-height: 28rpx;
			}
		}

	}
</style>